package hust.ning;

import hust.ning.jdo.ChatItem;
import hust.ning.jdo.DAO;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("serial")
public class HistoryServlet2 extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html;charset=UTF-8");
		resp.setHeader("Cache-Control","no-cache");
		PrintWriter out= resp.getWriter();

		String start = req.getParameter("start");
		Date d = new Date();
		try {
			d = sdf.parse(start);
		} catch (ParseException e) {
			e.printStackTrace();
			out.println("date format error ,use yyyy-MM-dd_HH:mm:ss.SSS");
			d = new Date();
		}
		List<ChatItem> list=null;
		list = DAO.getChatHistory(d);
		if(list.size()==0)
		{
			out.println("No Record~~<br/>");
			return ;
		}
		out.println("<p><a href='history?start=" +
				sdf.format(list.get(list.size()-1).getDate()) +
				"'>next page</a></p>");

		out.println("chat @ "+sdf.format(d)+"<br/>");
		for (ChatItem ci :list)
			out.println(ci.getId()+"\t"+sdf.format( ci.getDate())+"\t"+ci.getUid()+":"+ci.getContent()+"<br/>");
		out.close();
	}
	private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss.SSS");
	static {
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
